package com.heima.behavior.service.impl;

import com.heima.behavior.service.BehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BehaviorServiceImpl implements BehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult likeBehavior(LikesBehaviorDto dto) {

        //参数校验
        if(dto == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录用户
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        String key = BehaviorConstants.BLOG_LIKED_KEY + dto.getArticleId();
        Boolean member = stringRedisTemplate.opsForSet().isMember(key, apUser.getId().toString());
        //Double score = stringRedisTemplate.opsForZSet().score(key, apUser.getId().toString());
        //0 点赞   1 取消点赞
        short operation = dto.getOperation();
        if(BooleanUtils.isFalse(member)){
            //未点赞
            if(operation == 0){
                stringRedisTemplate.opsForSet().add(key,apUser.getId().toString());
            }
        }else{
            //已经点过赞
            if(operation == 1){
                stringRedisTemplate.opsForSet().remove(key,apUser.getId().toString());
            }

        }

        return ResponseResult.okResult("");
    }

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {

        if(dto == null){
            return   ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取登录用户
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        String key = BehaviorConstants.BLOG_READ_KEY + dto.getArticleId();


        //stringRedisTemplate.opsForZSet().add()


        return null;
    }

    /**
     * 点赞测试
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeBehaviorTest(LikesBehaviorDto dto) {
        //1.权限校验
        //

        return null;
    }
}
